// import { cancleGlobalTimer } from '@/common/common.js'

import md5 from 'js-md5'
const env = {
	'dev': 'https://xxxxxxx.com',
	'test': 'http://118.31.37.53:8008/api/',
	'beta': 'https://xxxxxxx.com',
	'prod': 'https://xxxxxxx.com',
}

// const baseUrl = env.test
// const Authorization = token ? `Bearer ${uni.getStorageSync("token")}` : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwMDA5LCJ1TmFtZSI6IjEzNDg3MzAyNDE0Iiwic2NvcGUiOjgsImV4cCI6MTY5OTM5NzA4MSwiaWF0IjoxNjk5MzI1MDgxfQ.M6P1-_RzA3VQY6PeE4jvXM6Q3X8q6RZRb1lcpDywJxY";
// const Authorization = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwMDA5LCJ1TmFtZSI6IjEzNDg3MzAyNDE0Iiwic2NvcGUiOjgsImV4cCI6MTY5OTM5NzA4MSwiaWF0IjoxNjk5MzI1MDgxfQ.M6P1-_RzA3VQY6PeE4jvXM6Q3X8q6RZRb1lcpDywJxY";

// // @/utils/request.js
// // #ifdef MP-WEIXIN
// const baseURL = "https://www.bradenhan.tech"
// // #endif 
// // #ifdef H5
// const baseURL = "http://118.31.37.53:8008/api/"
// // #endif

// 全局请求封装
const timeout = 180000;
const baseURL = 'https://p2papi.gratls.com.cn/'
// const baseURL = 'http://192.168.1.45/'
// const baseURL = 'https://cp.gratls.com.cn/'
// 全局请求封装
function request(config) {
	// console.log('请求参数':config);
	// console.log('请求参数：',config.data);
	if (config.data) {
		const timestamp = new Date().getTime();
		// const key = '69be7ed3'
		const key = uni.getStorageSync("num")+uni.getStorageSync("end")+uni.getStorageSync("code");
		config.data['timestamp'] = timestamp
		// console.log('排序前：',config.data);
		let sortedKeys = Object.keys(config.data).sort()
		let sortedObj = {}
		sortedKeys.forEach(key => {
			sortedObj[key] = config.data[key]
		})
		// console.log(timestamp);
		const sign = md5(JSON.stringify(sortedObj) + key)
		// const sign = uni.$md5(timestamp=${timestamp}&data=${JSON.stringify(sortedObj)});
		// console.log('拼接：',JSON.stringify(sortedObj) + key);
		// console.log('排序后：',sortedObj);
		// console.log('排序后字符串：',JSON.stringify(sortedObj));
		// console.log('sign:',sign);

		config.data['sign'] = sign
	}
	// console.log('最终提交：',config.data);
	let header = {
		// 'Content-Type': 'application/x-www-form-urlencoded'
	};
	if (uni.getStorageSync("token")) {
		header['Authorization'] = 'Bearer ' + uni.getStorageSync("token");
		// header['token'] = 'Bearer ' + uni.getStorageSync("token");
		// header['token'] = '' + uni.getStorageSync("token");
	} else {
		// uni.setStorageSync('token','Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwMDI5LCJ1TmFtZSI6IjEzNDg3MzAyNDE0Iiwic2NvcGUiOjgsImV4cCI6MTY5OTY2MzA0NSwiaWF0IjoxNjk5NTkxMDQ1fQ.zueTMpHL_dUaFYUtSo22fxtwkfLVTmyM1JCQ_iHi7gY')
		// header['Authorization'] = 'Bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwMDI5LCJ1TmFtZSI6IjEzNDg3MzAyNDE0Iiwic2NvcGUiOjgsImV4cCI6MTY5OTU4NTAxOCwiaWF0IjoxNjk5NTEzMDE4fQ.B0xCUfEZJsVKoj8ImdrONV4mEoYUxCiIHRfIE1i_z8s';
	}
	return new Promise((resolve, reject) => {
		uni.request(Object.assign(config, {
			url: baseURL + config.url,
			data: config.data,
			method: !config.method ? 'GET' : config.method.toLocaleUpperCase(),
			header: header,
			timeout: timeout, //超时时间
			withCredentials: true, //跨域请求时是否携带凭证（cookies）
			success: (res) => {
				// console.log(config);
				console.log(res);
				let statusCode = res.statusCode;
				//异常判断
				if (statusCode !== 200) {
					// uni.showToast({
					// 	title: res.msg,
					// 	icon: 'none',
					// 	duration: 2000
					// });
					if (statusCode == 401) {
						uni.setStorageSync('islogin', false)
						uni.setStorageSync('token', '')
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						});
						setTimeout(function() {
							uni.reLaunch({
								url: '/pages/inlet/login',
							})
						}, 2000)
						return
					}
					//返回异常信息
					// reject(res.obj || res.msg);
					resolve(res.data);
				} else {
					// console.log(res.data);
					var status = res.data.success
					var code = res.data.code
					if (!status && code == '401') {
						// cancleGlobalTimer()
						uni.setStorageSync('islogin', false)
						uni.setStorageSync('token', '')
						setTimeout(function() {
							uni.reLaunch({
								url: '/pages/inlet/login',
							})
						}, 2000)
						return
					}
					//返回正常信息
					resolve(res.data);
				}
			},
			fail: (error) => {
				//抛出错误
				// uni.setStorageSync('islogin',false)
				// uni.setStorageSync('token','')
				console.log('err', JSON.stringify(error))
				uni.showToast({
					title: '请求超时',
					icon: 'none',
					duration: 2000
				});
				reject(error);
			}
		}));
	})
}
export default request